package com.googlecode.fcgi4j.message;

import java.nio.ByteBuffer;

public class FCGINameValuePair {
	private String key;
	private String value;
	
	public FCGINameValuePair(String key, String value)
	{
		this.key = key;
		this.value = value;
	}
	
	public int getLength()
	{
		return countLength(key) + countLength(value);
	}
	
	public ByteBuffer getByteBuffer()
	{
		ByteBuffer byteBuffer = ByteBuffer.allocate(getLength());

		bufferLength(byteBuffer, key);
        bufferLength(byteBuffer, value);
        byteBuffer.put(key.getBytes());
        byteBuffer.put(value.getBytes());
		
        return byteBuffer;
	}
	
	private int countLength(String str)
    {
        int length = str.length();
        if(length < 0x80)
        {
            length += 1;
        }
        else
        {
            length += 4;
        }

        return length;
    }
	
	private void bufferLength(ByteBuffer byteBuffer, String str)
    {
        int length = str.length();

        if(length < 0x80)
        {
            byteBuffer.put((byte)length);
        }
        else
        {
            byteBuffer.putInt(length);
        }
    }
}
